<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="用户名字" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入用户名字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="证书编号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入证书编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="生成时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:userCert:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:userCert:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:userCert:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:userCert:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userCertList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="baseId" v-if="false" />
      <el-table-column label="用户名字" align="center" prop="nickName" />
      <el-table-column label="课程标题" align="center" prop="platformTitle" />
      <el-table-column label="证书编号" align="center" prop="code" />
      <el-table-column label="开始时间" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:userCert:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:userCert:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户证书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程标题" prop="platformId">
              <el-select style="width: 100%;" v-model="form.platformId" placeholder="请选择课程" clearable>
                <el-option v-for="item in platformList" :key="item.baseId" :label="item.title" :value="item.baseId">
                  <span style="float: left">{{ item.title }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    <dict-tag :options="dict.type.bmzt" :value="item.applyStatus" />
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-form-item required label="用户">
          <el-button type="success" plain @click="chooseUser" size="mini">选择用户
          </el-button>
        </el-form-item>
        <el-form-item v-if="currentUser.length!=0">
          <el-table :data="currentUser">
            <el-table-column label="用户账号" align="center" prop="userName" />
            <el-table-column label="用户姓名" align="center" prop="nickName" />
            <el-table-column label="手机号码" align="center" prop="phonenumber" />
            <el-table-column label="工作地点" align="center" prop="workPlace" />
            <el-table-column label="工作单位" align="center" prop="workUnit" />
            <el-table-column label="帐号状态" align="center" key="status">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status?'success':'danger'" size="mini">
                  {{scope.row.status?'启用':'禁用'}}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="beginTime">
              <el-date-picker style="width: 100%;" clearable v-model="form.beginTime" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker style="width: 100%;" clearable v-model="form.endTime" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户列表对话框 -->
    <el-dialog title="用户列表" :visible.sync="openUser" @close="closeUser" width="60%" append-to-body>
      <el-form :model="userParams" ref="userParams" size="small" :inline="true" label-width="75px">
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="userParams.userName" placeholder="请输入用户账号" clearable
            @keyup.enter.native="handleQueryUser" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="nickName">
          <el-input v-model="userParams.nickName" placeholder="请输入用户昵称" clearable
            @keyup.enter.native="handleQueryUser" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="userParams.phonenumber" placeholder="请输入手机号码" clearable
            @keyup.enter.native="handleQueryUser" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryUser">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryUser">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="userList">
        <el-table-column label="用户账号" align="center" prop="userName" />
        <el-table-column label="用户姓名" align="center" prop="nickName" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" />
        <el-table-column label="工作地点" align="center" prop="workPlace" />
        <el-table-column label="工作单位" align="center" prop="workUnit" />
        <el-table-column label="免学考试" align="center" key="allowExam">
          <template slot-scope="scope">
            {{scope.row.allowExam?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column label="帐号状态" align="center" key="status">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status?'success':'danger'" size="mini">
              {{scope.row.status?'启用':'禁用'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-user" @click="checkedUser(scope.row)">选择用户</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="totalUser>0" :total="total" :page.sync="userParams.pageNum" :limit.sync="userParams.pageSize"
        @pagination="getUserList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeUser">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listUserCert,
    getUserCert,
    delUserCert,
    addUserCert,
    updateUserCert
  } from "@/api/business/userCert";
  import {
    platformList
  } from "@/api/business/platform";
  import {
    listUser,
    getInfoByUserName
  } from "@/api/business/businessUser";
  export default {
    name: "UserCert",
    dicts: ['bmzt'],
    data() {
      return {
        // 课程列表
        platformList: [],
        openUser: false,
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户证书表格数据
        userCertList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 结束时间时间范围
        daterangeCreateTime: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userName: undefined,
          nickName: undefined,
          code: undefined,
          createTime: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          baseId: [{
            required: true,
            message: "主键不能为空",
            trigger: "blur"
          }],
          platformId: [{
            required: true,
            message: "课程标题不能为空",
            trigger: "blur"
          }],
          code: [{
            required: true,
            message: "证书编号不能为空",
            trigger: "blur"
          }],
          beginTime: [{
            required: true,
            message: "开始时间不能为空",
            trigger: "blur"
          }],
          endTime: [{
            required: true,
            message: "结束时间不能为空",
            trigger: "blur"
          }],
        },
        userParams: {
          pageNum: 1,
          pageSize: 10,
          userName: undefined,
          nickName: undefined,
          phonenumber: undefined,
          status: undefined,
          workPlace: undefined,
          workUnit: undefined,
          loginIp: undefined,
          loginDate: undefined,
        },
        userList: [],
        totalUser: 0,
        currentUser: []
      };
    },
    created() {
      this.getList();
    },
    methods: {
      chooseUser() {
        this.openUser = true
        this.resetQueryUser()
      },
      closeUser() {
        this.openUser = false
        this.$forceUpdate()
      },
      getPlatformList() {
        platformList().then(response => {
          this.platformList = response.data;
        });
      },
      /** 查询用户证书列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        listUserCert(this.queryParams).then(response => {
          this.userCertList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询用户信息列表 */
      getUserList() {
        listUser(this.userParams).then(response => {
          this.userList = response.rows;
          this.totalUser = response.total;
        });
      },
      /** 搜索按钮操作 */
      handleQueryUser() {
        this.userParams.pageNum = 1;
        this.getUserList();
      },
      /** 重置按钮操作 */
      resetQueryUser() {
        this.resetForm("userParams");
        this.handleQueryUser();
      },
      checkedUser(row) {
        this.currentUser = []
        this.currentUser.push(row)
        this.form.userName = row.userName
        this.openUser = false
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.currentUser = []
        this.form = {
          baseId: undefined,
          userName: undefined,
          platformId: undefined,
          answerId: undefined,
          code: undefined,
          beginTime: undefined,
          endTime: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeCreateTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.baseId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getPlatformList();
        this.open = true;
        this.title = "添加用户证书";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        this.getPlatformList();
        const baseId = row.baseId || this.ids
        getUserCert(baseId).then(response => {
          this.loading = false;
          this.form = response.data;
          getInfoByUserName(this.form.userName).then(res => {
            this.currentUser.push(res.data)
          })
          this.open = true;
          this.title = "修改用户证书";
        });
      },
      /** 提交按钮 */
      submitForm() {
        if (this.currentUser.length == 0) {
          this.$modal.msgError("请选择用户！");
        } else {
          this.$refs["form"].validate(valid => {
            if (valid) {
              this.buttonLoading = true;
              if (this.form.baseId != null) {
                updateUserCert(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              } else {
                addUserCert(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              }
            }
          });
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const baseIds = row.baseId || this.ids;
        this.$modal.confirm('是否确认删除用户证书编号为"' + baseIds + '"的数据项？').then(() => {
          this.loading = true;
          return delUserCert(baseIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {}).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/userCert/export', {
          ...this.queryParams
        }, `userCert_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
